package com.cxmx.escort.config.sdk;

import com.huawei.iotplatform.client.NorthApiException;
import com.huawei.iotplatform.client.dto.CommandDTOV4;
import com.huawei.iotplatform.client.dto.PostDeviceCommandInDTO2;
import com.huawei.iotplatform.client.dto.PostDeviceCommandOutDTO2;
import com.huawei.iotplatform.client.invokeapi.SignalDelivery;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class NBOceanConnectService {

    @Value("${nb.oceanconnect.serviceId}")
    private String serviceId;


    @Value("${nb.oceanconnect.callback}")
    private String callbackAddress;


    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    NBIoTService nbIoTService;

    public Object unlock(String imei, String cmd) {
        PostDeviceCommandInDTO2 pdcInDTO = new PostDeviceCommandInDTO2();
        pdcInDTO.setDeviceId(imei);
        pdcInDTO.setCallbackUrl(callbackAddress);
        pdcInDTO.setExpireTime(0);
        pdcInDTO.setMaxRetransmit(3);

        CommandDTOV4 dtov4 = new CommandDTOV4();
        dtov4.setMethod("openDoorDownData");
        dtov4.setServiceId(serviceId);
        Map<String, Object> cmdParam = new HashedMap();
        cmdParam.put("command", 1);
        cmdParam.put("openDoor",cmd);
        dtov4.setParas(cmdParam);

        pdcInDTO.setCommand(dtov4);

        try {
        SignalDelivery signalDelivery = new SignalDelivery(nbIoTService.getNorthApiClient());

            PostDeviceCommandOutDTO2 postDeviceCommandOutDTO2 = signalDelivery.postDeviceCommand(pdcInDTO,nbIoTService.getAppId(),null);
            logger.error(postDeviceCommandOutDTO2.toString());
            return postDeviceCommandOutDTO2;
        } catch (NorthApiException e) {
            System.out.println(e.toString());
            return null;
        }
    }
}
